package com.hddf.project.auth.filter;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.kommii.log.LogNames;
import org.kommii.log.LogWriter;

import com.hddf.project.auth.pojos.User;
import com.hddf.project.auth.service.CookieService;
import com.hddf.project.auth.service.MongoDB_Query;
import com.hddf.project.auth.service.WebLoginService;
import com.mongodb.DBObject;

public class AuthFilter implements Filter {
	private FilterConfig config; //从配置文件里面读filter里的参数  
	private  String login_url = null;
	private  String no_permission_url = null;
	public void destroy() {
		System.out.println("filter destory");
		config = null;
	}

	public void doFilter(ServletRequest paramServletRequest,
			ServletResponse paramServletResponse, FilterChain paramFilterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) paramServletRequest;// 强制转换
		HttpServletResponse response = (HttpServletResponse) paramServletResponse;// 强制转换
		System.out.println("do filter");
		 CookieService cs = CookieService.getInstance();
	        WebLoginService wls = WebLoginService.getInstance();
	        MongoDB_Query mq = MongoDB_Query.getInstance();
	        Map<String,Object> m = null;
	        String auth = "";
			Cookie ctoken = cs.getCookieByName(request, "to");
			Cookie ctime = cs.getCookieByName(request, "ti");
			boolean b = (null!=ctime && !"".equals(ctime.getValue()));
			boolean b2 = (null!=ctoken  && !"".equals(ctoken.getValue()));
			if(b && b2){
	        	String web_token = ctoken.getValue();
				String web_time = ctime.getValue();
				//System.out.println("========555"+web_time);
				//mq.getSimpleUserByWebToken(web_token);
				m = wls.checkWebToken(web_token,web_time);
				String str = (String)m.get("msg");
				if(!"".equals(str)){
					response.sendRedirect(login_url);
				}else{
					auth = "ok";
					m.put("auth", auth);
					request.setAttribute("user", m);
					String webtoken = (String)m.get("web_token");
					cs.addCookie(response, "to",webtoken , 0);
					
					String uri = request.getRequestURI();
					uri = uri.replace("/", "");
					System.out.println(uri);
					User u = (User)m.get("u");
					String permission = u.getPermission();
					boolean rs = false; 
					if("all".equals(permission)){
						//m.put("permission", "ok");
						rs = true;
					}else{
						List<DBObject> list = mq.getAuthByUser(u.getPermission());
						for(int i=0;i<list.size();i++){
							rs = list.get(i).get("url").toString().contains(uri);
							if(rs)
								break;
						}
					}
					if(rs){
						String logs = "user id: "+u.getId()+" , user name: "+u.getUsername()+", url: "+uri;
						LogWriter.writeLog(LogNames.jsp_page,null,logs);
						paramFilterChain.doFilter(paramServletRequest, paramServletResponse);
					}else{
						response.sendRedirect(no_permission_url);
					}
				}
	        }else{
				response.sendRedirect(login_url);
	        }
		/** 
		 * RequestDispatcher rd = request.getRequestDispatcher("login.jsp");   //request的重定位，服务端跳转 
		 * rd.forward(request, response); 
		 */
		//response.sendRedirect("/login.html");// 过滤完之后跳转，这样跳转是从定向，客户端跳转
		// 如果不写这个，那么服务器就不会响应客户端的请求，也就是不会有response产生 
		//paramFilterChain.doFilter(paramServletRequest, paramServletResponse);
	}

	public void init(FilterConfig paramFilterConfig) throws ServletException {
		this.config = paramFilterConfig;
		this.login_url = config.getInitParameter("redirect_url_login");
		this.no_permission_url = config.getInitParameter("no_permission_message");
		
	}
}
